//
//  Date-Extension.swift
//  KKWB
//
//  Created by KSY-iOS on 17/1/16.
//  Copyright © 2017年 KK. All rights reserved.
//

import Foundation

extension Date {
    
    static func creatDateString(creatStr: String) -> String {
        // 1.创建时间格式化对象
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "en")
        
        // 2.将时间字符串，转化为时间Date
        guard let creatDate = fmt.date(from: creatStr) else {
            return ""
        }
        
        // 3.创建当前时间
        let nowDate = Date()
        
        // 4.计算创建时间和当前时间的时间差
        let interval = Int(nowDate.timeIntervalSince(creatDate))
        
        // 5.对时间处理
        // 5.1 显示刚刚
        if interval < 60 {
            return "刚刚"
        }
        
        // 5.2 显示 X分钟之前
        if interval < 60 * 60 {
            return "\(interval / 60)分钟前"
        }
        
        // 5.3 显示 X小时之前
        if interval < 60 * 60 * 24 {
            return "\(interval / (60 * 60))小时前"
        }
        
        // 5.4 显示 昨天 HH:mm
        let calendar = Calendar.current
        
        if calendar.isDateInYesterday(creatDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: creatDate)
            return timeStr
        }
        
        // 5.5 显示一年以内
        let cmps = calendar.dateComponents(Set<Calendar.Component>([.year]), from: creatDate, to: nowDate)
        if cmps.year! < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr = fmt.string(from: creatDate)
            return timeStr
        }
        
        // 5.6 一年以上 yyyy-MM-dd HH:mm
        
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeStr = fmt.string(from: creatDate)
        return timeStr
    }
}
